<!--#include virtual="/menu.cgi?path=/projects/opensource/libCoroutine/docs" -->

<UL>

<table cellpadding=0 cellspacing=0 border=0 width=90%>
<tr>
<td>

<h2>Overview</h2>

libCoroutine is a simple stackfull coroutine implementation. On unix platforms, the implementation uses ucontext if available or with setjmp/longjmp otherwise except on OSX where some assembly is used. On windows, fibers are used. <br>
<p>

<h3>Main</h3>

First you'll need to create a coro instance to represent the C stack that was allocated to run the host program's main() function:

<pre>
Coro *mainCoro = Coro_new();
Coro_initializeMainCoro(mainCoro);
</pre>

<h3>Starting</h3>

To create a coroutine:
<pre>
Coro *newCoro = Coro_new();
Coro_startCoro_(currentCoro, newCoro, aContext, aCallback);
</pre>

currentCoro should be a pointer to the currenting running coroutine (which would be mainCoro, if this is the first corountine you're creating). aCallback is a function pointer for the function which will be called when the coroutine starts and aContext is the argument that will be passed to the callback function.

<h3>Switching</h3>

To switch to the coroutine:

<pre>
Coro_switchTo_(currentCoro, nextCoro);
</pre>

<h3>Freeing</h3>

<pre>
Coro_free(aCoro);
</pre>

Note that you can't free the currently running coroutine as this would free the current C stack.

<h3>Stacks</h3>

You can check to see whether a corouinte has nearly exhausted its stack space by calling:

<pre>
Coro_stackSpaceAlmostGone(aCoro);
</pre>

This returns 1 if the remaining stack space is less than CORO_STACK_SIZE_MIN. 
<p>
The define CORO_STACK_SIZE can be used to adjust the default stack size. There is also a #ifdef on USE_VALGRIND which, when enabled, will register stack switches with valgrind, so it won't be confused.

<h3>Chaining</h3>

A trick to provide effectively get unlimited stack space while keeping stack allocations small is to periodically call Coro_stackSpaceAlmostGone() and create a new Coro in which to continue the computation when the stack gets low.

<h2>Credits</h2>


I (Steve Dekorte) mostly just put together bits of code from other folks to make this library. Russ Cox deserves the most credit currently for the portable ucontext code. Some history:
 <p>
	Originally based on Edgar Toernig's Minimalistic cooperative multitasking 
	(http://www.goron.de/~froese/) <br>
	reorg by Steve Dekorte and Chis Double <br>
	Symbian and Cygwin support by Chis Double <br>
	Linux/PCC, Linux/Opteron, Irix and FreeBSD/Alpha, ucontext support by Austin Kurahone <br>
	FreeBSD/Intel support by Faried Nawaz <br>
	Mingw support by Pit Capitain <br>
	Visual C support by Daniel Vollmer <br>
	Solaris support by Manpreet Singh <br>
	Fibers support by Jonas Eschenburg <br>
	Ucontext arg support by Olivier Ansaldi <br>
	Ucontext x86-64 support by James Burgess and Jonathan Wright <br>
	Russ Cox for the newer portable ucontext implementions.<br>

</td>
</tr>
</table>

<br><br><br>
</UL>
